<?php
	/*
		This file is part of Lproxy.
	
	    Lproxy is free software: you can redistribute it and/or modify
	    it under the terms of the GNU General Public License as published by
	    the Free Software Foundation, either version 3 of the License, or
	    (at your option) any later version.
	
	    Lproxy is distributed in the hope that it will be useful,
	    but WITHOUT ANY WARRANTY; without even the implied warranty of
	    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	    GNU General Public License for more details.
	
	    You should have received a copy of the GNU General Public License
	    along with Lproxy.  If not, see <http://www.gnu.org/licenses/>.
	    
	    Code version 0.0.1
	*/

	$BEGIN_SIGN = '-B-';
	$END_SIGN = '-E-';
	
	function Dec2Hex($str)
	{
		$r = dechex($str);
		if(strlen($r) == 1)
		{
			$r = '0'.$r;
		}
		return $r;
	}
	
	function Hex2Dec($str)
	{
		return hexdec($str);
	}
	
	function LEncode($str)
	{
		return base64_encode($str);
	}
	
	function LDecode($str)
	{
		return base64_decode($str);
	}
	
	function Debug($str)
	{
		$DEBUG = 0;
		if($DEBUG == 1)
			print $str;
	}
	function Error($str)
	{
		global $BEGIN_SIGN,$END_SIGN;
		$info = "HTTP/1.0 500 $str \r\n";
		$info .= "Content-Type: text/html\r\n\r\n";
		$info .= "<html><body><b>error ".$str."</b></body></html>\n";
		print $info;
		print $BEGIN_SIGN;
		print LEncode($info);
		print $END_SIGN;
		exit;
	}
	
	if(isset($_REQUEST['test']) == true)
	{
		print $BEGIN_SIGN;
		print LEncode('OK');
		print $END_SIGN;
		exit;
	}

	if(isset($_REQUEST['address']) == false || isset($_REQUEST['port']) == false || isset($_REQUEST['data']) == false)
	{
		Error("Remote information error ");
	}
	if(isset($_REQUEST['TIME_OUT']) == false || isset($_REQUEST['LENGTH']) == false)
	{
		Error("Server param error ");
	}
	$LENGTH = LDecode($_REQUEST['LENGTH']);
	$TIME_OUT = LDecode($_REQUEST['TIME_OUT']);
	$address = LDecode($_REQUEST['address']);
	$port = LDecode($_REQUEST['port']);
	$data = LDecode($_REQUEST['data']);
	Debug("host = ".$address."<br />\r\n"."port = ".$port."<br />\r\n");
	$fp = fsockopen($address,$port,$errno,$errstr,$TIME_OUT);
	if(!$fp)
	{
		Error("Connect error ".$errstr." ".$errno);
	}
	
	if(false == fwrite($fp,$data))
	{
		Error("Send data error ");
	}
	//Receive data
	while(!feof($fp))
	{
		$r = fread($fp,$LENGTH);
		if(false == $r)
		{
			fclose($fp);
			Error("Recieve data error");
		}
		print $BEGIN_SIGN.LEncode($r).$END_SIGN;
	}
	fclose($fp);
	exit;
?>
